package com.one.common.model.http;



import com.one.common.R;
import com.one.common.config.CMemoryData;
import com.one.common.config.CPersisData;
import com.one.common.config.RouterPath;
import com.one.common.manager.RouterManager;
import com.one.common.model.http.callback.ObserverOnNextListener;
import com.one.common.model.http.callback.ObserverOnResultListener;
import com.one.common.model.http.exception.ApiException;
import com.one.common.utils.Logger;
import com.one.common.utils.MyToast;
import com.one.common.utils.Toaster;
import com.one.common.view.base.BaseActivity;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * @author nanchen
 * @fileName RetrofitRxDemoo
 * @packageName com.nanchen.retrofitrxdemoo
 * @date 2016/12/12  14:48
 * 接口请求观察者
 */

public class ApiObserver<T> implements Observer<T> {
    private ObserverOnNextListener<T> mListener;
    private BaseActivity activity;

    public ApiObserver(ObserverOnNextListener<T> listener, BaseActivity activity) {
        this.mListener = listener;
        this.activity = activity;
    }

    public ApiObserver(ObserverOnResultListener<T> listener, BaseActivity mActivity) {
        this.mListener = getListener(listener);
        this.activity = mActivity;
    }

    public ApiObserver(ObserverOnNextListener<T> listener) {
        this.mListener = listener;
    }

    public ApiObserver(ObserverOnResultListener<T> listener) {
        getListener(listener);
    }

    /**
     * 当错误提示为默认提示时使用getListener
     *
     * @param listener 监听
     * @return
     */
    public ObserverOnNextListener<T> getListener(final ObserverOnResultListener<T> listener) {
        return new ObserverOnNextListener<T>() {
            @Override
            public void onNext(T t) {
                listener.onResult(t);
            }

            @Override
            public void onError(String errorCode, String msg) {
                Logger.d("okhttp error 报错了11 "+msg);
                Toaster.showLongToast(msg, MyToast.FAIL);
            }
        };
    }


    @Override
    public void onComplete() {
        //Toast.makeText(App.getInstance(), "获取数据完成！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onError(Throwable e) {
        Logger.e("onError "+e.getLocalizedMessage());
        if (e instanceof SocketTimeoutException) {
            Toaster.showLongToast(R.string.request_service_timeout,MyToast.FAIL);
            mListener.onError(ErrorConstant.APP_ERROR_TIMEOUT, activity.getResources().getString(R.string.request_service_timeout));
        } else if (e instanceof ConnectException) {
            Toaster.showLongToast(R.string.request_service_timeout,MyToast.FAIL);
            mListener.onError(ErrorConstant.APP_ERROR_TIMEOUT, activity.getResources().getString(R.string.request_service_timeout));
        } else if (e instanceof ApiException) {
            String error = ((ApiException) e).getErrorMsg();
            // 登录超时
            if (error.equals(ErrorConstant.LOGIN_OUT_TIME)) {
                Toaster.showLongToast("登录信息失效，请重新登录！",MyToast.FAIL);
                CPersisData.setIsLogin(false);
                if(activity!=null) {
                    RouterManager.getInstance().goAndFinish(activity, RouterPath.LOGIN_PAGE);
                } else {
                    RouterManager.getInstance().go(RouterPath.LOGIN_PAGE);
                }
            } else {
                mListener.onError(((ApiException) e).getErrorCode(), ((ApiException) e).getErrorMsg());
            }
        } else if (e instanceof HttpException) {
            Toaster.showLongToast(R.string.request_service_error,MyToast.FAIL);
            mListener.onError(ErrorConstant.APP_ERROR_HTTPEXCEPTION, activity.getResources().getString(R.string.request_service_error));

        } else if(e instanceof UnknownHostException){
            Toaster.showLongToast(R.string.request_net);
            mListener.onError(ErrorConstant.APP_ERROR_FAIL, activity.getResources().getString(R.string.request_net));
        } else {
            Toaster.showLongToast(e.getMessage(),MyToast.FAIL);
            mListener.onError(ErrorConstant.APP_ERROR_FAIL, e.getMessage());
            e.printStackTrace();
        }
        cancelLoading();
    }

    @Override
    public void onNext(T t) {
        if (mListener != null) {
            mListener.onNext(t);
        }
        Logger.d("okhttp onNext onNext ");
        cancelLoading();
    }

    /**
     * 关闭网络弹窗
     */
    private void cancelLoading(){
        if(activity != null){
            activity.cancelLoading();
        }
    }

}
